<template>
  <div>
    <a-modal
      width="600px"
      :title="title === 'edit' ? '编辑驱动' : '上传驱动'"
      :visible="visible"
      :confirmLoading="confirmLoading"
      :closable="!isUpload"
      :keyboard="!isUpload"
      :maskClosable="!isUpload"
      @cancel="handleCancel"
    >
      <section>
        <a-form :form="form" class="pass-form" ref="formTemp">
          <a-form-item label="驱动名称" v-bind="formItemLayout">
            <a-input
              v-decorator="[
                'fileName',
                {
                  rules: [{ max: 128, message: '长度不能超过128' }]
                }
              ]"
              placeholder="请输入驱动名称"
            ></a-input>
          </a-form-item>
          <a-form-item label="驱动类型" v-bind="formItemLayout">
            <a-select
              v-decorator="[
                'driverType',
                {
                  rules: [{ required: true, message: '不能为空!' }]
                }
              ]"
              allowClear
              placeholder="请选驱动类型"
            >
              <a-select-option
                v-for="(columns, i) in selectColumns.driverType"
                :key="i"
                :value="columns.value"
                >{{ columns.label }}</a-select-option
              >
            </a-select>
          </a-form-item>
          <a-form-item label="操作系统类型" v-bind="formItemLayout">
            <a-select
              v-decorator="[
                'osType',
                {
                  rules: [{ required: true, message: '不能为空!' }]
                }
              ]"
              placeholder="请选择操系统类型"
            >
              <a-select-option
                v-for="(columns, i) in selectColumns.osType"
                :key="i"
                :value="columns.value"
                >{{ columns.label }}</a-select-option
              >
            </a-select>
          </a-form-item>
          <a-form-item label="操作系统位数" v-bind="formItemLayout">
            <a-select
              v-decorator="[
                'cpuBits',
                {
                  rules: [{ required: true, message: '不能为空!' }]
                }
              ]"
              placeholder="请选择操作系统"
            >
              <a-select-option
                v-for="(columns, i) in selectColumns.cpuBits"
                :key="i"
                :value="columns.value"
                >{{ columns.label }}</a-select-option
              >
            </a-select>
          </a-form-item>
          <a-form-item label="版本信息" v-bind="formItemLayout">
            <a-input
              v-decorator="[
                'version',
                {
                  rules: [
                    { required: true, message: '不能为空!' },
                    { max: 64, message: '长度不能超过64' },
                    { validator: validVersion }
                  ]
                }
              ]"
              placeholder="xx.xx.xx.xx"
            ></a-input>
          </a-form-item>
          <a-form-item label="变更履历" v-bind="formItemLayout">
            <a-input
              v-decorator="[
              'description',
                {
                  rules: [ { max: 128, message: '长度不能超过128' } ]
                }
              ]"
              placeholder="请输入变更履历"
            ></a-input>
          </a-form-item>
          <a-form-item label="上传附件" v-bind="formItemLayout">
            <upload-temp
              ref="uploadTemp"
              :data.sync="uploadData"
              @done="handlerUpload('done', $event)"
              @remove="handlerUpload('remove')"
              @resetValid="resetValid"
              @uploading="
                status => {
                  this.isUpload = status;
                }
              "
              v-decorator="[
                'filePath',
                {
                  rules: [{ required: true, message: '不能为空!' }]
                }
              ]"
            ></upload-temp>
          </a-form-item>
          <a-form-item :style="{ dispaly: 'none' }">
            <input type="hidden" v-decorator="['fileSize']" />
          </a-form-item>
          <a-form-item :style="{ dispaly: 'none' }">
            <input type="hidden" v-decorator="['_id']" />
          </a-form-item>
        </a-form>
      </section>
      <template slot="footer">
        <a-button
          key="back"
          :loading="isUpload"
          @click="handleCancel"
          >取消</a-button
        >
        <a-button
          key="submit"
          type="primary"
          :loading="isUpload"
          @click="handleOk"
          >确定</a-button
        >
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Emit, Vue } from "vue-property-decorator";
import { selectColumns } from "@/common/AntSelectConfig";
import { Upload as UploadTemp } from "@/components";
import { drive_upload, drive_edit, drive_finish } from "@/api/drive";
import { IDriver } from "@/model/Driver";
import { CloneDeep } from "@/utils";
import formItemLayout from "@/common/FormItemLayout";
import { validVersion } from "@/common/validate";
import { UploadFinish } from "@/utils/VEnum";

@Component({
  components: { UploadTemp }
})
export default class DriveModdal extends Vue {
  private validVersion: any = validVersion;
  private selectColumns: any = selectColumns;
  private isUpload: boolean = false;
  private visible: boolean = false;
  private confirmLoading: boolean = false;
  private form: any = {};
  private formItemLayout: any = formItemLayout;
  private uploadData: any = {};

  @Prop({ type: String }) title!: string;

  created() {
    this.form = this.$form.createForm(this);
  }

  resetValid(fileds: string[]) {
    this.form.resetFields(fileds);
  }

  handlerUpload(check: string, file: any) {
    if (check == "remove") {
      this.form.setFieldsValue({ filePath: null, fileSize: null });
      delete this.uploadData.filePath;
      delete this.uploadData.fileName;
    }
    if (check == "done") {
      const { filePath, fileSize } = file;
      this.form.setFieldsValue({ filePath, fileSize });
    }
  }

  showModal(check: string) {
    this.visible = true;
    this.$nextTick(() => {
      const vm: any = this.$refs.uploadTemp;
      vm.initTemp(check);
    });
  }

  async handleOk(): Promise<any> {
    this.form.validateFields((err: any, values: any) => {
      if (!err) {
        this.submit(values);
      }
      return null;
    });
  }
  
  async isUploadFn(form: any) {//校验是否上传附件完毕
    try {
      const { filePath, fileSize } = form;
      const { data } = await drive_finish({ filePath, fileSize });
      if (data.errNo === 0) {
        const { errNo } = data.item;
        if (errNo == UploadFinish.SUCCESS) {
          return true;
        } else {
          this.$message.warning("文件服务未完成。请稍等...")
          return false;
        }
      }
    } catch (error) {
      return false;
    }
  }

  @Emit("submit")
  async submit(form: any) {
    if (!form) return null;
    const bool = await this.isUploadFn(form);
    if (!bool) return null;
    try {
      if (this.title === "edit") {
        const _editForm: IDriver = CloneDeep(form);
        delete _editForm._id;
        delete _editForm.md5;
        const { data } = await drive_edit(form._id, _editForm);
        this.handleCancel();
        this.$message.success("编辑成功");
        return true;
      } else {
        const { data } = await drive_upload(form);
        if (data.errNo == 0) {
          this.handleCancel();
          this.$message.success("操作成功");
          return true;
        }
      }
    } catch (error) {
      return false;
    }
  }

  handleCancel() {
    const vm: any = this.$refs.uploadTemp;
    this.visible = false;
  }

  initFormData(check: string, values: IDriver) {
    if (check == "edit") {
      this.$nextTick(() => {
        const { httpPath } = values;
        const datas = httpPath.split("/");
        const driverName = datas[datas.length - 1];
        this.uploadData = { driverName };
      });
    } else {
      this.uploadData = {};
    }
    const {
      _id,
      fileName,
      fileSize,
      driverType,
      osType,
      cpuBits,
      version,
      description,
      filePath
    } = values;
    setTimeout(() => {
      this.form.setFieldsValue({
        _id,
        fileName,
        fileSize,
        driverType,
        osType,
        cpuBits,
        version,
        description,
        filePath
      });
    }, 0)
  }
}
</script>
